package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean checkAndDeduct(AccountDeductVo accountDeductVo) {
        int result = userAccountMapper.cheackAndDeduct(accountDeductVo.getAmount(), accountDeductVo.getUserId());
        if (result > 0) {
            this.addUserAccountDetail(accountDeductVo.getUserId(),accountDeductVo.getAmount(),accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,accountDeductVo.getOrderNo());
            return true;
        }
        return false;
    }

    private void addUserAccountDetail(Long userId, BigDecimal amount, String content, String accountTradeTypeDeposit, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(content);
        userAccountDetail.setTradeType(accountTradeTypeDeposit);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);

    }

    /**
     * 添加用户账户信息
     * 当用户注册或特定情况下需要初始化用户账户时调用此方法
     * 此方法负责创建一个新的用户账户实例，设置初始值，并将其插入到数据库中
     *
     * @param userId 用户ID，用于关联用户和其账户信息
     */
    @Override
    public void addUserAccount(Long userId) {
        // 创建一个新的用户账户实例
        UserAccount userAccount = new UserAccount();
        // 设置用户账户的用户ID
        userAccount.setUserId(userId);
        // 设置用户账户的初始总额为1000
        userAccount.setTotalAmount(new BigDecimal("1000"));
        // 设置用户账户的初始可用金额为1000
        userAccount.setAvailableAmount(new BigDecimal("1000"));
        // 将用户账户信息插入到数据库中
        userAccountMapper.insert(userAccount);
    }
}
